import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main(){
  runApp(new MaterialApp(home: new MyApp()));
}
class MyApp extends StatefulWidget{
  final String mUserName="userName";
  final _userNameControllor=new TextEditingController();


  @override
  Widget build(BuildContext context){
    save() async{
      SharedPreferences prefs=await SharedPreferences.getInstance();
      prefs.setString(mUserName, _userNameControllor.value.text.toString());

    }
    Future<String> get() async{
      var userName;

      SharedPreferences prefs=await SharedPreferences.getInstance();
      userName=prefs.getString(mUserName);
      return userName;
    }
    return new Builder(builder: (BuildContext contextt){
      return new Scaffold(
        appBar: AppBar(
          title:Text("SharedPreferences"),
        ),
        body: Center(
          child: new  Builder(builder: (BuildContext context){
            return
                Column(
                  children: <Widget>[
                    TextField(
                      controller: _userNameControllor,
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.only(top:10.0),
                        icon:Icon(Icons.perm_identity),
                        labelText: "请输入用户名",
                        helperText: "注册时填写的名字"),
                      ),
                    ElevatedButton(
                      child: Text("储存"),
                      onPressed: (){
                        save();
                        ScaffoldMessenger.of(context).showSnackBar(
                           SnackBar(content: Text("数据储存成功"),)
                        );
                      }),
                    ElevatedButton(
                      child:Text("获取"),
                        onPressed:(){
                        Future<String> userName=get();
                        userName.then((String userName){
                          ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(content: Text("数据储存成功:$userName"),)
                             );
                          });
                        }),
                  ],
                );
        }),
        ),
      );
    });
  }

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    throw UnimplementedError();
  }
}